function bvc = voi_BVCoords(hfile, voi, bbox)
% VOI::BVCoords  - return BV system coords for a voi
%
% FORMAT:       bvc = voi.BVCoords(voi [, bbox])
%
% Input fields:
%
%       voi         number of name of VOI
%       bbox        optional VMR bounding box (default: 256^3 TAL VMR)
%
% Output fields:
%
%       bvc         Nx3 coords (e.g. to index into 256^3 VMR space)

% Version:  v0.7g
% Build:    9040105
% Date:     Apr-01 2009, 5:38 AM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'voi') || ...
   (~ischar(voi) && ~isa(voi, 'double')) || ...
    isempty(voi)
    error( ...
        'BVQXfile:BadArguments', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
if nargin < 3 || ...
   ~isstruct(bbox) || ...
    numel(bbox) ~= 1 || ...
    numel(fieldnames(bbox)) ~= 8 || ...
   ~all(strcmp(fieldnames(bbox), ...
        {'BBox'; 'DimXYZ'; 'FCube'; 'RadCnv'; 'ResXYZ'; 'QuatB2T'; 'QuatT2B'}))
    bbox = struct( ...
        'BBox',    [0, 0, 0; 255, 255, 255], ...
        'DimXYZ',  [256, 256, 256], ...
        'FCube',   256, ...
        'RadCnv',  1, ...
        'ResXYZ',  [1, 1, 1], ...
        'QuatB2T', [0, 0, -1, 129; -1, 0, 0, 129; 0, -1, 0, 129; 0, 0, 0, 1], ...
        'QuatT2B', [0, -1, 0, 129; 0, 0, -1, 129; -1, 0, 0, 129; 0, 0, 0, 1]);        
end
bc = bvqxfile_getcont(hfile.L);
numvois = numel(bc.VOI);
if ischar(voi)
    voiok = false;
    for vc = 1:numvois
        if ~isempty(regexpi(bc.VOI(vc).Name, lower(voi(:)')))
            voiok = true;
            break;
        end
    end
    if ~voiok
        error( ...
            'BVQXfile:InvalidName', ...
            'Named VOI not found.' ...
        );
    end
    voi = vc;
else
    voi = real(voi(:)');
    if any(isinf(voi) | isnan(voi) | voi < 1 | voi > numvois) || ...
        numel(unique(fix(voi))) ~= numel(voi)
        error( ...
            'BVQXfile:BadArgument', ...
            'Invalid VOI selection.' ...
        );
    end
    voi = fix(voi);
end

% get voi
voi = bc.VOI(voi);

% initialize bvc
bvc = voi.Voxels;

% transform?
if strcmpi(bc.ReferenceSpace, 'tal')
    bvc = bvcoordconv(bvc, 'tal2bvi', bbox);
end
